package com.mingren.controller;

import com.mingren.annotation.AuthCheck;
import com.mingren.common.BaseResponse;
import com.mingren.common.ResultUtils;
import com.mingren.constant.UserConstant;
import com.mingren.exception.BusinessException;
import com.mingren.exception.ErrorCode;
import com.mingren.manager.CosManager;
import com.qcloud.cos.model.COSObject;
import com.qcloud.cos.model.COSObjectInputStream;
import com.qcloud.cos.utils.IOUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 * 文件上传、文件下载 接口测试
 *
 * @author 曹宏福
 * @version 1.0
 */
@RestController
@RequestMapping("/file")
@Slf4j
public class FileController {

    @Resource
    private CosManager cosManager;

    /**
     * 测试文件上传
     *
     * @param multipartFile:文件流
     * @return
     */
    @PostMapping("/test/upload")
    public BaseResponse<String> testFileUpload(MultipartFile multipartFile) {
        //设置文件目录 日期/文件来源名称
        String filename = multipartFile.getOriginalFilename();
        String filepath = new SimpleDateFormat("yyyy-MM-dd").format(new Date()) + "/" + filename;

//        //需求是根据当前日期存放我们文件-根据日期生成目录
//        //日期-java基础-SimpleDateFormat
//        String format = new SimpleDateFormat("yyyy-MM-dd").format(new Date());
//        String dir = format  + "/";
        File file = null;
        //上传文件逻辑
        try {
            /**
             * 这行代码调用了 File 类的静态方法 createTempFile 来创建一个临时文件。
             * filepath：这个参数通常作为临时文件名称的前缀
             * 表示临时文件名称的后缀
             */
            file = File.createTempFile(filepath, null);
            /**
             * 将上传的文件内容从内存或临时存储位置转移到之前创建的临时文件中
             */
            multipartFile.transferTo(file);
            cosManager.putObject(filepath, file);
            //返回可访问地址
            return ResultUtils.success(filepath);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        } finally {
            //删除文件
            if (file != null) {
                boolean delete = file.delete();
                if (!delete) {
                    //如果删除文件失败,返回错误信息
                    log.error("file delete error, filepath = {}", filepath);
                }
            }
        }
    }

    /**
     * 测试文件下载
     *
     * @param filepath:文件路径
     * @return
     */
    @PostMapping("/test/down")
    @AuthCheck(mustRole = UserConstant.ADMIN_ROLE)
    public void testFiledown(String filepath, HttpServletResponse response) throws IOException {
        COSObjectInputStream cosObjectInput = null;
        try {
            COSObject cosobject = cosManager.getObject(filepath);
            cosObjectInput = cosobject.getObjectContent();
            byte[] bytes = IOUtils.toByteArray(cosObjectInput);
            // 设置响应头
            response.setContentType("application/octet-stream;charset=UTF-8");
            response.setHeader("Content-Disposition", "attachment; filename=" + filepath);
            // 写入响应
            //返回显示字节码
            response.getOutputStream().write(bytes);
            response.getOutputStream().flush(); //刷新输出流，确保所有数据都被发送到客户端
        } catch (Exception e) {
            log.error("file download error, filepath = " + filepath, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "下载失败");
        }finally {
            // 释放流
            if (cosObjectInput != null) {
                cosObjectInput.close();
            }
        }
    }
}
